package com.saitan.demo;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.saitan.demo.utils.PermissionUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SplashActivity extends AppCompatActivity {
    public static final int INSTALL_PERMISS_CODE = 1;

    @BindView(R.id.txt_loading)
    TextView mTxtLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        PermissionUtils.initPermission(getApplicationContext(), SplashActivity.this);
    }

    //获取权限
    @Override
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.RequestCode && grantResults != null) {
            //自动更新
            boolean haveInstallPermission = getApplicationContext().getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                go();
            } else {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, INSTALL_PERMISS_CODE);
            }
        }
    }

    //结果页
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INSTALL_PERMISS_CODE) {
            if (resultCode == RESULT_OK) {
                go();
            } else {
                log("无法自动更新，未授权安装应用");
            }
        }
    }

    //设置调试信息
    private void log(String message) {
        mTxtLoading.post(new Runnable() {
            @Override
            public void run() {
                mTxtLoading.setText(message);
            }
        });
    }

    //跳转
    private void go() {
        Class c = GlassActivity.class;

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, c));
                finish();
            }
        }, 1000);
    }
}
